/**
 * account service created for reference only, it will be upated later
 * **/
import { Injectable } from '@angular/core';
import {Http, URLSearchParams, Headers, RequestOptions} from "@angular/http";
import './../../../../../rxjs-operators'; // Operators
@Injectable()
export class AccountService {

  private headers = new Headers({'Content-Type': 'application/json'}); // set body as json
  private url = '/api/account';
  private rolesurl = '/api/role';
  constructor(private http: Http) { }

// 新增，编辑后保存账户
  save(account:any): Promise<any>{
    if(account.id){
      return this.update(account);
    }else{
      return this.create(account);
    }
  }
  //新增账户
  create(account: any): Promise<any> {
    let options = new RequestOptions({ headers: this.headers });
    const url = `${this.url}`;
    return this.http
      .put(this.url, JSON.stringify(account), options)
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }
  //更新账户
  update(account: any): Promise<any> {
    let options = new RequestOptions({ headers: this.headers });
    const url = `${this.url}`;
    return this.http
      .post(this.url, JSON.stringify(account), options)
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }
  //删除账户
  delete(id: number): Promise<any> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url,{headers: this.headers})
      .toPromise()
      .then((res) => res.json())
      .catch(this.handleError);
  }
  // 获取账户列表
  getItems (pn,ps,keywords,sortby,asc): Promise<any> {
    let params = new URLSearchParams();
    params.set('pn', pn);
    params.set('ps', ps);
    if(keywords){
      params.set('keyword',keywords );
    }
    if(sortby){
      params.set('sortBy', sortby);
    }
    if(asc){
      params.set('asc', asc);
    }
    return this.http.get(this.url, { search: params }).toPromise().then(response => {
      return response.json()});
  }
  // error handler
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
  // 获取用户角色
  getRoles (): Promise<any> {
    return this.http.get(this.rolesurl).toPromise().then(response => {
      return response.json();
    }).catch(this.handleError);
  }
}
